import 'dart:convert';
import 'dart:io';

import 'package:dk_flutter_base/dk_core.dart';
import 'package:flutter_device_info/flutter_device_info.dart';
import 'package:quiver/strings.dart';

///通用验签工具类
class CommonSignUtil {
  static const String TIMESTAMP = "timestamp";

  static const String HEADER_X_APP_ID = "X-App-ID";
  static const String HEADER_X_DEVICE_ID = "X-Device-ID";
  static const String HEADER_X_DEVICE_INFO = "X-Device-Info";
  static const String HEADER_AUTHORIZATION = "Authorization";
  static const String HEADER_SIGN = "sign";
  static const String DEVICE_UUID = "device-uuid";

  ///为请求参数添加时间戳
  static void addTimeStampForMap(Map<String, dynamic> queryParameters) {
    queryParameters[TIMESTAMP] =
        (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
  }

  /*static void addTimeStampForBody(dynamic body) {
    queryParameters[TIMESTAMP] =
        (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
  }*/

  ///为请求的url进行md5，通常为get和delete
  static String addUrlMd5ForMap(Map<String, dynamic> queryParameters) {
    var stringBuffer = StringBuffer();
    stringBuffer.write(Env.value?.netWorkConfig?.clientSecret);
    queryParameters.forEach((key, value) {
      stringBuffer.write(key.toString() + value.toString());
    });
    stringBuffer.write(Env.value?.netWorkConfig?.clientSecret);
    return generateMd5(stringBuffer.toString()).toUpperCase();
  }

  ///为请求的body进行md5，通常为post和put
  static String addBodyMd5ForMap(Map<String, dynamic> bodyParameters) {
    if (mapEmpty(bodyParameters)) {
      return "";
    }
    var stringBuffer = StringBuffer();
    stringBuffer.write(Env.value?.netWorkConfig?.clientSecret);
    stringBuffer.write(json.encode(bodyParameters));
    stringBuffer.write(Env.value?.netWorkConfig?.clientSecret);
    return generateMd5(stringBuffer.toString()).toUpperCase();
  }

  /*static String addMd5ForBody(Map<String, dynamic> queryParameters) {
    var stringBuffer = StringBuffer();
    stringBuffer.write(Env.value.clientSecret);
    queryParameters.forEach((key, value) {
      stringBuffer.write(key.toString() + value.toString());
    });
    stringBuffer.write(Env.value.clientSecret);
    return generateMd5(stringBuffer.toString()).toUpperCase();
  }*/

  static String mToken = "";

  ///为请求添加请求头和验签，区分Android和iOS，Android分开设置，iOS一次性全部设置
  static Future<Map<String, dynamic>> getCommonHeaders(
      String verifyData) async {
    Map<String, dynamic> result = Map();
    Map<String, dynamic> commonParam = await getCommonParam();

    if (Platform.isAndroid) {
      result[HEADER_X_DEVICE_INFO] =
          /*commonParam*/
          json.encode(commonParam) /*utf8.encode(json.encode(commonParam))*/;
      result[HEADER_SIGN] = verifyData;
      result[HEADER_X_APP_ID] = Env.value?.netWorkConfig?.appId;
      result[HEADER_X_DEVICE_ID] = commonParam[DEVICE_UUID] ?? "";
      if (isBlank(mToken)) {
        FlutterDeviceInfo deviceInfo = FlutterDeviceInfo();
        result[HEADER_AUTHORIZATION] =
            await deviceInfo.getCacheInfo("SP_USER", "token");
      } else {
        result[HEADER_AUTHORIZATION] = mToken;
      }
    } else if (Platform.isIOS) {
      commonParam[HEADER_SIGN] = verifyData;
      return commonParam;
    }
    return result;
  }

  ///获取native中保存的header信息，参考[FlutterDeviceInfo.headerInfo]
  static Future<Map<String, dynamic>> getCommonParam() async {
    Map<String, dynamic> commonParam = Map();
    FlutterDeviceInfo deviceInfo = FlutterDeviceInfo();
    Map<dynamic, dynamic> androidInfo = await deviceInfo.headerInfo;
    if (null != androidInfo) {
      androidInfo.forEach((dynamic key, dynamic value) {
        commonParam[key] = value;
      });
    }
    /*if (Platform.isAndroid) {
      commonParam["ClientId"] = await deviceInfo.getDebugInfo(
          "SP_PUSH", "push_id"); // 个推clientId
      String latitude =
          await deviceInfo.getDebugInfo("loc_baidu", "loc_latitude");
      String longitude =
          await deviceInfo.getDebugInfo("loc_baidu", "loc_longitude");
      if (isNotEmpty(latitude) && isNotEmpty(longitude)) {
        commonParam["loc_latlng"] = latitude + "_" + longitude;
      }
      commonParam["loc_city"] =
          await deviceInfo.getDebugInfo("loc_baidu", "loc_city");
      commonParam["loc_address"] =
          await deviceInfo.getDebugInfo("loc_baidu", "loc_address");
      return commonParam;
    }*/
    return commonParam;
  }
}
